// pages/submitGoods/submitGoods.js
var config = require("../../config.js")
var util = require("../../utils/MD5.js")
var request = require("../../utils/request.js");
var tableControllor = require("../../utils/tableControllor.js");
var g = getApp().globalData;
var ext = {};
var timer = null;
var time = 60;
// var sensors = require('../../utils/sensorsdata.min.js');
const common = require('../../common/js/common.js')
Page({
    data: {
        zpid: 6,
        tableId: 11,
        ShopNo: 100233,
        ztInfo: {
            C_CODE: "34234",
            C_ZPNAME: "佳人有约",
            N_CID: 361,
            RegionName: "娱乐区",
            TableName: "佳人有约",
        },
        callStatus: true,
        people: "",
        mebInfo: {
            C_MB_PHONE: "",
        },
        keywords: "",
        mebno: "",
        callStatus: true,
        setMember: false,
        setNumber: false,
        noMember: true,
        gradeId: "",
        pageIndex: 1,
        pageSize: 100,
        OrderNo: "",
        delIndex: [],
        ogList: [],
        num: 0,
        nMeb: true,
        callText: "呼叫",
        submitStatus: true,


        cwf: 1, // 默认有餐位费 1、0
        action: 1, //0下单 1 加菜 2 退菜 
        PeopleCount: 0,
        addStr: [],
        IsExamine: 1,
    },
    onLoad(options) {
        this.data.ShopNo = g.SHOP_NO;
        console.log(common.prevPage().data)
        const prevData = common.prevPage().data
        this.setData({
            storeEwm: prevData.storeEwm,
            ztInfo: prevData.ztInfo,
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        wx.getStorage({
            key: 'zt-info',
            success: rs => {
                console.log(rs)
                this.setData({
                    ztInfo: rs.data,
                })
                wx.getStorage({
                    key: 'result-list',
                    success: res => {
                        console.log(res.data)
                        for (var i = 0; i < res.data.gList.length; i++) {
                            if (res.data.gList[i].Batchings) {
                                var feed = [];
                                for (var j = 0; j < res.data.gList[i].Batchings.length; j++) {
                                    if (res.data.gList[i].Batchings[j].checked) {
                                        feed.push(res.data.gList[i].Batchings[j].Batching_Name);
                                    }
                                }
                                if (feed.length > 0) {
                                    res.data.gList[i].C_GoodsFeed = "口味：" + feed.join("，")
                                }
                            }

                            if (res.data.gList[i].currentPractice) {
                                res.data.gList[i].C_GoodsTodo = "做法：" + res.data.gList[i].currentPractice.Practice_Name
                            }
                        }
                        this.setData({
                            goodsList: res.data.gList,
                            totalNum: res.data.totalNum,
                            totalPrice: res.data.totalPrice
                        })
                        // this.getExtConfig(rs.data.C_ORD_NO);
                        if (rs.data.C_ORD_NO) {
                            this.data.OrderNo = rs.data.C_ORD_NO;
                            if (!rs.data.mebno) {
                                this.setData({
                                    nMeb: false,
                                })
                            }
                        }
                        this.data.gList = res.data.gList
                    },
                })
            },
        })
    },

    // 呼叫
    callWaiter(CallType) {
        if (!this.data.callStatus) {
            return
        }
        var MD5 = util.md5(`OrderNo&TID&CallType&ShopNo=${this.data.ztInfo.C_ORD_NO}*${this.data.ztInfo.ID}*${CallType}*${this.data.ShopNo}`).toUpperCase();
        var data = {
            bNo: 2223,
            OrderNo: this.data.ztInfo.C_ORD_NO,
            TID: this.data.ztInfo.ID,
            CallType: CallType,
            ShopNo: this.data.ShopNo,
            MD5,
        }

        if (this.data.callStatus) {
            this.setData({
                callStatus: false,
            })
            wx.request({
                url: config.requestUrl,
                data,
                success: res => {
                    if (res.data.code === "100") {
                        wx.showToast({
                            title: '已呼叫服务员',
                        })
                        timer = setInterval(() => {
                            if (time > 1) {
                                time--;
                                this.setData({
                                    callText: time + "s",
                                })
                            } else {
                                this.setData({
                                    callText: "呼叫",
                                    callStatus: true,
                                })
                                time = 60;
                                clearInterval(timer)
                            }
                        }, 1000)
                    }
                }
            })
        }
    },


    clearMember() {
        wx.showModal({
            title: '提示',
            content: '确认不使用会员吗？',
            success: res => {
                if (res.confirm) {
                    this.setData({
                        noMember: true,
                        mebInfo: null,
                        mebno: "",
                    })
                }
            }
        })
    },

    showCallOptions() {
        if (!this.data.callStatus) {
            return;
        }
        this.callWaiter(1);
    },
    

    withoutMember() {
        wx.showModal({
            title: '提示',
            content: '填写会员信息的话会有很多优惠权限，记得在点菜的时候添加哦，不然后面就添不了了',
            showCancel: false,
        })
    },

    getExtConfig(no) {
        wx.getExtConfig({
            success: res => {
                ext = res.extConfig;
                if (no) {
                    this.getOrderInfo();
                }
            }
        })
    },

    minusFood(ev) {
        if (this.data.goodsList[ev.currentTarget.dataset.i].N_NUM > 1) {
            this.data.goodsList[ev.currentTarget.dataset.i].N_NUM--;
            this.data.gList[ev.currentTarget.dataset.i].N_NUM--;
            this.data.totalNum--;
            var totalPrice = 0;
            for (var i = 0; i < this.data.goodsList.length; i++) {
                if (this.data.goodsList[i].currentPractice) {
                    totalPrice += this.data.goodsList[i].currentPractice.Practice_Price;
                }

                if (this.data.goodsList[i].Batchings) {
                    for (var j = 0; j < this.data.goodsList[i].Batchings.length; j++) {
                        if (this.data.goodsList[i].Batchings[j].checked) {
                            totalPrice += this.data.goodsList[i].Batchings[j].Batching_Price * this.data.goodsList[i].Batchings[j].num;
                        }
                    }
                }

                totalPrice += this.data.goodsList[i].SALE_PRICE * this.data.goodsList[i].N_NUM;
            }
            totalPrice = parseFloat(totalPrice).toFixed(2)
            wx.setStorage({
                key: 'result-list',
                data: {
                    gList: this.data.goodsList,
                    totalPrice,
                    totalNum: this.data.totalNum
                },
                success: res => {
                    this.setData({
                        totalPrice,
                        goodsList: this.data.goodsList
                    })
                }
            })
        } else {
            if (this.data.goodsList.length > 1) {
                wx.showModal({
                    title: '提示',
                    content: '本菜只剩最后一个了，确认要删除本菜吗？',
                    success: res => {
                        if (res.confirm) {
                            this.data.gList.splice(ev.currentTarget.dataset.i, 1);
                            this.data.goodsList.splice(ev.currentTarget.dataset.i, 1);
                            this.data.totalNum--;
                            var totalPrice = 0;
                            for (var i = 0; i < this.data.goodsList.length; i++) {
                                if (this.data.goodsList[i].currentPractice) {
                                    totalPrice += this.data.goodsList[i].currentPractice.Practice_Price;
                                }

                                if (this.data.goodsList[i].Batchings) {
                                    for (var j = 0; j < this.data.goodsList[i].Batchings.length; j++) {
                                        if (this.data.goodsList[i].Batchings[j].checked) {
                                            totalPrice += this.data.goodsList[i].Batchings[j].Batching_Price * this.data.goodsList[i].Batchings[j].num;
                                        }
                                    }
                                }

                                totalPrice += this.data.goodsList[i].SALE_PRICE * this.data.goodsList[i].N_NUM;
                            }
                            totalPrice = parseFloat(totalPrice).toFixed(2)
                            wx.setStorage({
                                key: 'result-list',
                                data: {
                                    gList: this.data.goodsList,
                                    totalPrice,
                                    totalNum: this.data.totalNum
                                },
                                success: res => {
                                    this.setData({
                                        totalPrice,
                                        totalNum: this.data.totalNum,
                                        goodsList: this.data.goodsList
                                    })
                                }
                            })
                        }
                    }
                })
            } else {
                wx.navigateBack({
                    delta: 1
                })
            }
        }
    },

    addFood(ev) {
        this.data.goodsList[ev.currentTarget.dataset.i].N_NUM++;
        this.data.gList[ev.currentTarget.dataset.i].N_NUM++;
        this.data.totalNum++;
        var totalPrice = 0;
        for (var i = 0; i < this.data.goodsList.length; i++) {
            if (this.data.goodsList[i].currentPractice) {
                totalPrice += this.data.goodsList[i].currentPractice.Practice_Price;
            }

            if (this.data.goodsList[i].Batchings) {
                for (var j = 0; j < this.data.goodsList[i].Batchings.length; j++) {
                    if (this.data.goodsList[i].Batchings[j].checked) {
                        totalPrice += this.data.goodsList[i].Batchings[j].Batching_Price * this.data.goodsList[i].Batchings[j].num;
                    }
                }
            }

            totalPrice += this.data.goodsList[i].SALE_PRICE * this.data.goodsList[i].N_NUM;
        }
        totalPrice = parseFloat(totalPrice).toFixed(2)
        wx.setStorage({
            key: 'result-list',
            data: {
                gList: this.data.goodsList,
                totalPrice,
                totalNum: this.data.totalNum
            },
            success: res => {
                this.setData({
                    totalPrice,
                    totalNum: this.data.totalNum,
                    goodsList: this.data.goodsList
                })
            }
        })
    },

    getOrderInfo() {
        var str = `ShopNo&OrderNo=${this.data.ShopNo}*${this.data.ztInfo.C_ORD_NO}`;
        var md5 = util.md5(str);
        var data = {
            bNo: 4004,
            ShopNo: this.data.ShopNo,
            OrderNo: this.data.ztInfo.C_ORD_NO,
            MD5: md5.toUpperCase()
        };

        request(data, (data) => {
            if (data.code === "100") {
                if (data.Examine == 1) {
                    this.data.ogList = data.gbase;
                    this.order();
                } else {
                    wx.showModal({
                        title: "提示",
                        content: '请等待商家简单确认之后再点菜',
                        showCancel: false,
                    })
                }
            }
        })
    },
    // 点菜1
    getTableDetail() {
        tableControllor.queryTableUser({
            TID: g.tableId,
            ShopNo: this.data.ShopNo,
        }, data => {
            console.log('-----点菜')
            console.log(data)
            //TableInfo.PEOPLECOUNT 用餐人数、Tables_State 使用状态（0正常1并桌2合桌）、Table_State 状态（0未使用1已使用2已预订3打扫中）
            if (data.TableInfo.TABLE_STATE == 1) {
                this.getZtGoods()
            } else if (data.TableInfo.TABLE_STATE == 2) { // 2已预订
                this.data.ztInfo.C_ORD_NO = data.OrderNo;
                this.data.OrderNo = data.OrderNo;
                this.getOrderInfo();
            } else {
                if (this.data.num > 0) {
                    this.data.ztInfo.C_ORD_NO = "";
                    this.data.OrderNo = "";
                    this.openTable();
                } else {
                    wx.showModal({
                        title: '提示',
                        content: '请填写用餐人数',
                        showCancel: false,
                        success: res => {
                            this.setData({
                                setNumber: true,
                            })
                        }
                    })
                }
            }
        })
    },

    setKeywords(ev) {
        this.setData({
            keywords: ev.detail.value
        })
    },

    /**
     * 获取会员列表
     */
    getMenberList() {
        if (!/^1\d{10}/g.test(this.data.keywords)) {
            wx.showModal({
                title: '提示',
                content: '请填写正确的手机号码',
                showCancel: false,
            })
            return;
        }
        var str = `ShopNo&keywords&gradeId&pageIndex&pageSize=${this.data.ShopNo}*${this.data.keywords}*0*${this.data.pageIndex}*${this.data.pageSize}`;
        var md5 = util.md5(str);
        wx.showLoading({
            title: '加载中',
        })
        var data = {
            bNo: 1204,
            ShopNo: this.data.ShopNo,
            keywords: this.data.keywords,
            gradeId: 0,
            pageIndex: this.data.pageIndex,
            pageSize: this.data.pageSize,
            keytype: -1,
            MD5: md5.toUpperCase()
        };

        wx.request({
            url: config.requestUrl,
            data,
            success: res => {
                var d = res.data.replace(/\(|\)/g, "");
                var t = JSON.parse(d);
                if (t.mebdt.length > 0) {
                    for (var i = 0; i < t.mebdt.length; i++) {
                        if (t.mebdt[i].C_MB_NAME.length > 20) {
                            t.mebdt[i].C_MB_NAME = t.mebdt[i].C_MB_NAME.substr(0, 20) + "..."
                        }
                    }
                    wx.setStorage({
                        key: 'member',
                        data: t.mebdt[0],
                    })
                    this.setData({
                        noMember: false,
                        mebInfo: t.mebdt[0],
                        mebno: t.mebdt[0].C_MB_NO,
                    })
                    this.hideDialog();
                } else {
                    wx.showModal({
                        title: '提示',
                        content: '抱歉，暂无会员信息',
                        showCancel: false,
                    })
                }
                wx.hideLoading()
            }
        })
    },

    def() {},
    sureOrder() {
        if (this.data.ztInfo.ZTSTATE == "空闲") {
            if (this.data.num > 0) {
                this.openTable();
            } else {
                wx.showModal({
                    title: '提示',
                    content: '请填写用餐人数',
                    showCancel: false,
                    success: res => {
                        this.setData({
                            setNumber: true,
                        })
                    }
                })
            }
        } else {
            this.order();
        }
    },
    // 开桌
    openTable() {
        wx.showLoading({
            title: '正在开桌',
            mask: true,
        })
        this.setData({
            submitDisabled: true
        })
        var str = `tid&Remark&Ponut&C_MB_NO&C_MB_PHONE&lcodes&lprice&wids&wname&CWF&ShopNo=${this.data.ztInfo.ID}**${this.data.num}*${this.data.mebno}*${this.data.mebInfo.C_MB_PHONE}**0***${parseFloat(this.data.ztInfo.StoreCWF) * parseFloat(this.data.num)}*${this.data.ShopNo}`;
        var md5 = util.md5(str);
        var data = {
            bNo: 2221,
            tid: this.data.ztInfo.ID,
            Remark: "",
            Ponut: this.data.num,
            C_MB_NO: this.data.mebno,
            C_MB_PHONE: this.data.mebInfo.C_MB_PHONE,
            lcodes: "",
            lprice: 0,
            wids: "",
            wname: "",
            CWF: parseFloat(this.data.ztInfo.StoreCWF) * parseFloat(this.data.num),
            ShopNo: this.data.ShopNo,
            MD5: md5.toUpperCase()
        };

        wx.request({
            url: config.requestUrl,
            data,
            success: res => {
                console.log('2212-------------------')
                console.log(res)
                if (res.data.code === "100") {
                    wx.showToast({
                        title: res.data.msg,
                    })
                    this.getZtGoods();
                    // this.order("o");
                } else {
                    this.setData({
                        submitDisabled: false
                    })
                }
            }
        })
    },

    getZtGoods() {
        var str = `TID&ShopNo=${this.data.ztInfo.ID}*${this.data.ShopNo}`;
        var md5 = util.md5(str);
        var data = {
            bNo: 2212,
            TID: this.data.ztInfo.ID,
            ShopNo: this.data.ShopNo,
            MD5: md5.toUpperCase()
        };

        request(data, res => {
            var arr = [];
            for (var i = 0; i < res.GoodsList.length; i++) {
                arr.push({
                    N_GOODS_ID: res.GoodsList[i].ID,
                    N_GB_ID: res.GoodsList[i].N_GB_ID,
                    N_NUM: 1,
                    N_REALPRICE: res.GoodsList[i].SALE_PRICE,
                    C_GOODS_NAME: res.GoodsList[i].GOODS_NAME,
                    G_CODE: res.GoodsList[i].GOODS_CODE,
                    C_GoodsTodo: res.GoodsList[i].GoodsTodo, // 做法名称
                    C_GoodsFeed: res.GoodsList[i].GoodsFeed, // 口味名称
                    ZFAmount: res.GoodsList[i].ZFAmount, // 做法金额
                    N_GoodsFeedJe: res.GoodsList[i].GoodsFeedJe, // 口味金额
                    C_GoodsRemark: res.GoodsList[i].GoodsRemark || "", // 备注
                    N_ServiceFee: 0,
                    N_PACKID: 0,
                    N_TableID: this.data.ztInfo.ID,
                    N_ISPACK: 0,
                    N_LPTC: 0,
                    GZT: res.GoodsList[i].GZT, // 商品状态，判断是正常商品还是删菜
                })
            }
            this.data.ztGoods = arr;
            this.order("o");
        })
    },
    // 点菜
    order(t) {
        if (this.data.submitStatus) {
            this.data.submitStatus = false;
        } else {
            return;
        }
        wx.showLoading({
            title: '处理中',
            mask: true,
        })
        var sublist = [];
        var oIdx = this.data.ogList.length;
        var glist = this.data.ogList;
        var addStr = [];
        for (var i = 0; i < this.data.gList.length; i++) {
            var C_GoodsTodo = "";
            var N_GoodsFeedJe = 0;
            var C_GoodsFeed = "";
            var C_GoodsRemark = "";
            var tastArr = [];
            var ZFAmount = 0;
            if (this.data.gList[i].currentPractice) {
                sublist.push({
                    "ID": this.data.gList[i].currentPractice.ID,
                    "Type": 0,
                    "GoodsID": this.data.gList[i].ID,
                    "Count": 0,
                    "Price": this.data.gList[i].currentPractice.Practice_Price,
                })
                C_GoodsTodo = "做法：" + this.data.gList[i].currentPractice.Practice_Name;
                ZFAmount = this.data.gList[i].currentPractice.Practice_Price
            };

            if (this.data.gList[i].Batchings) {
                for (var j = 0; j < this.data.gList[i].Batchings.length; j++) {
                    if (this.data.gList[i].Batchings[j].checked) {
                        sublist.push({
                            "ID": this.data.gList[i].Batchings[j].ID,
                            "Type": 1,
                            "GoodsID": this.data.gList[i].ID,
                            "Count": this.data.gList[i].Batchings[j].num,
                            "Price": this.data.gList[i].Batchings[j].Batching_Price
                        })
                        N_GoodsFeedJe += this.data.gList[i].Batchings[j].Batching_Price * this.data.gList[i].Batchings[j].num;
                        tastArr.push(this.data.gList[i].Batchings[j].Batching_Name)
                    }
                }
            }

            if (tastArr.length > 0) {
                C_GoodsFeed = "口味：" + tastArr.join(",")
            }

            if (this.data.gList[i].C_GoodsRemark) {
                C_GoodsRemark += "备注：" + this.data.gList[i].C_GoodsRemark
            }

            var GZT = 0;
            if (this.data.OrderNo) {
                GZT = 3;
            }

            var GoodsGg = this.data.gList[i].C_SPNAME;
            if (!this.data.gList[i].C_SPNAME) {
                GoodsGg = this.data.gList[i].SPECIFICATION
            }

            glist.push({
                "N_GOODS_ID": this.data.gList[i].ID,
                "N_GB_ID": this.data.gList[i].N_GB_ID,
                "N_NUM": this.data.gList[i].N_NUM,
                "N_REALPRICE": this.data.gList[i].SALE_PRICE,
                "C_GOODS_NAME": this.data.gList[i].GOODS_NAME,
                "G_CODE": "",
                C_GoodsTodo,
                "C_GoodsFeed": C_GoodsFeed,
                "ZFAmount": ZFAmount,
                N_GoodsFeedJe,
                C_GoodsRemark,
                GoodsGg,
                "N_ServiceFee": 0,
                "N_PACKID": 0,
                "N_ISPACK": 0,
                "N_LPTC": 0,
                "GZT": GZT,
            })
        }

        for (var i = 0; i < glist.length; i++) {
            glist[i].MaxXh = i + 1;
        }

        if (this.data.ztInfo.C_ORD_NO) {
            for (var i = oIdx; i < glist.length; i++) {
                addStr.push(i + 1);
            }
        } else {
            if (this.data.ztGoods) {
                for (var i = 0; i < this.data.ztGoods.length; i++) {
                    glist.push(this.data.ztGoods[i]);
                }
            } else {
                for (var i = 0; i < this.data.goodsList.length; i++) {
                    glist.push(this.data.goodsList[i]);
                }
            }
        };

        if (addStr.length == 0) {
            addStr = ""
        } else {
            addStr = addStr.join(",");
        }

        for (var k = 0; k < sublist.length; k++) {
            sublist[k].CurIndex = k;
            sublist[k].MaxXh = sublist.length;
        };

        var IsExamine = 0;
        if (this.data.OrderNo) {
            IsExamine = 1;
        }

        for (var i = 0; i < glist.length; i++) {
            glist[i].N_TableID = this.data.ztInfo.ID;
        }
        console.log('glist-------------------')
        console.log(glist)
        console.log(sublist)
        var str = `ShopNo&mebNo&sublist&opid&OrderNo=${this.data.ShopNo}*${this.data.mebno}*${JSON.stringify(sublist)}*0*${this.data.OrderNo}`;
        var md5 = util.md5(str);
        var data = {
            bNo: 4003,
            opid: 0,
            OrderNo: this.data.OrderNo,
            mebNo: this.data.mebno,
            glist: JSON.stringify(glist),
            sublist: JSON.stringify(sublist),
            Addstr: addStr,
            Upstr: "",
            IsExamine,
            Delstr: '',
            ReDelstr: "",
            ShopNo: this.data.ShopNo,
            TID: this.data.ztInfo.ID,
            SMDC: 1,
            MD5: md5.toUpperCase()
        };
        console.log(data)
        // return
        request(data, (data) => {
            wx.hideLoading();
            if (data.code === "100") {
                // sensors.track("submitOrder", data)
                console.log('成功---------')
                console.log(this.data.gList)
                console.log(this.data.totalPrice)
                console.log(this.data.totalNum)
                this.data.ztInfo.C_ORD_NO = data.OrderNo
                wx.setStorage({
                    key: 'zt-info',
                    data: this.data.ztInfo,
                    success: res => {
                        var url = '/pages/orderSuccess/orderSuccess?t=a';
                        if (t == "o") {
                            url = '/pages/orderSuccess/orderSuccess?t=o';
                        }
                        wx.redirectTo({
                            url,
                        })
                    }
                })
                wx.removeStorage({
                    key: 'result-list',
                })
            } else {
                wx.showModal({
                    title: '提示',
                    content: data.msg,
                })
            }
        }, "POST")
    },

    fullNumber() {
        this.setData({
            num: this.data.ztInfo.PEOPLESIZE,
            people: this.data.ztInfo.PEOPLESIZE,
        })
        this.hideDialog();
    },

    hideDialog() {
        this.setData({
            setNumber: false,
            setMember: false,
        })
    },

    showDialog(ev) {
        var i = ev.currentTarget.dataset.i;
        if (i == 1) {
            this.setData({
                setMember: true,
            })
        } else {
            this.setData({
                setNumber: true,
            })
        }
    },

    setPeopleSize(ev) {
        if (parseInt(ev.detail.value) > this.data.ztInfo.PEOPLESIZE) {
            wx.showModal({
                title: '提示',
                content: '本桌推荐人数为' + this.data.ztInfo.PEOPLESIZE + "人，本次自动设置为满桌",
                showCancel: false,
                success: res => {
                    this.setData({
                        people: this.data.ztInfo.PEOPLESIZE
                    })
                }
            })
        } else {
            this.setData({
                people: ev.detail.value
            })
        }
    },

    sureNumber() {
        this.setData({
            num: this.data.people
        })
        this.hideDialog();
    }
})